import { InjectionToken } from "tsyringe";
import { tryGet } from "../utils/tryGet";
import { CONFIG, getSender } from "../tokens/core";
import { login } from "../apis/login";
import { COMMAND_LOGIN_SUCCESS, COMMAND_UPDATE_DEVICE_SETTING } from "../tokens/command";
import { ACCOUNT_NAME, DEVICE_NAME, DEVICE_UUID, TOKEN } from "../tokens/const";
import { CURRENT_TASK, DEVICE_SETTING } from "../tokens";

export function execCommand(command: InjectionToken, ...args: any[]) {
    const config = tryGet(CONFIG)
    const sender = getSender()
    switch (command) {
        case `COMMAND_CLEAR_CACHE`:
            log(`清空缓存`)
            config.clear();
            break;
        case `COMMAND_EXIT`:
            log(`退出`)
            exit();
            break;
        case `COMMAND_LOGIN`:
            const [data] = args;
            login(data).catch(e => {
                console.error(`login fail`, e)
            })
            break;
        case COMMAND_UPDATE_DEVICE_SETTING:
            const [setting] = args;
            config.set(DEVICE_SETTING, setting)
            sender.send(DEVICE_SETTING, setting)
            break;
        case COMMAND_LOGIN_SUCCESS:
            const loginSuccess = args[0]
            config.set(TOKEN, loginSuccess.token)
            config.set(DEVICE_UUID, loginSuccess.device_uuid)
            config.set(DEVICE_NAME, loginSuccess.device_name)
            config.set(ACCOUNT_NAME, loginSuccess.username)
            break;
        case CURRENT_TASK:
            sender.send(CURRENT_TASK, args[0])
            break;
        default:
            console.log(`收到未处理命令${command as string}`)
            break;
    }
}